package com.example.clientsideapplication;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class ViewMerchantOfferService extends IntentService {

	private Socket socket;
	private SharedPreferences pref;
	private String serverAddress;
	private int serverSocket;
	private final static String MY_LOGIN = "myAppLogIn";
	private ObjectInputStream inputStream;
	private ObjectOutputStream outputStream;
	private DataPackage outputMessage;
	private DataPackage inputMessage;
	private final String VIEW_MERCHANT_OFFER_ACTION = "android.intent.action.VIEW_MERCHANT_OFFER_ACTION";
	private ArrayList<Offer> offerArrayList;

	public ViewMerchantOfferService() {
		super("ViewMerchantOfferService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		serverAddress = intent.getStringExtra("serverAddress");
		serverSocket = intent.getIntExtra("serverSocket", 21111);

		try {
			socket = new Socket(serverAddress, serverSocket);
			inputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
			outputStream = new ObjectOutputStream(socket.getOutputStream());

			pref = getSharedPreferences(MY_LOGIN, Context.MODE_PRIVATE);
			Integer idMerchant = pref.getInt("idMerchant", -1);

			outputMessage = new DataPackage(5, idMerchant);
			outputStream.writeObject(outputMessage);

			inputMessage = (DataPackage) inputStream.readObject();
			
			offerArrayList = (ArrayList<Offer>) inputMessage.getDataPackage();
			
			Intent offerIntent = new Intent();
			offerIntent.setAction(VIEW_MERCHANT_OFFER_ACTION);
		
			offerIntent.putExtra("offerArrayList", offerArrayList);
			offerIntent.putExtra("serverAddress", serverAddress);
			offerIntent.putExtra("serverSocket", serverSocket);
			
			sendBroadcast(offerIntent);

			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}